package com.lsyw.intergrate.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.googlecode.aviator.AviatorEvaluator;
import com.lsyw.intergrate.common.StringUtil;
import com.lsyw.intergrate.entity.*;
import com.lsyw.intergrate.service.*;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lsyw.intergrate.entity.common.PageInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsyw.intergrate.common.Result;
import org.springframework.util.CollectionUtils;
import lombok.AllArgsConstructor;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import io.swagger.annotations.Api;
import lombok.Data;

/**
 * <p>
 * 手动采样任务监测表 前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2024-01-19
 */
@Api(tags = "手动采样任务监测表")
@RestController
@RequestMapping("/m-sampling-task-detection")
public class MSamplingTaskDetectionController {

    @Autowired
    private MSamplingTaskService mSamplingTaskService;
    @Autowired
    private MSamplingTaskDetectionService mSamplingTaskDetectionService;
    @Autowired
    private MSamplingTaskDetectionInfoService mSamplingTaskDetectionInfoService;
    @Autowired
    private MSamplingTaskDetectionItemService mSamplingTaskDetectionItemService;
    @Autowired
    private JcyzSdShuiService jcyzSdShuiService;
    @Autowired
    private JcyzSdTrService jcyzSdTrService;
    @Autowired
    private JcyzSdDaqiService jcyzSdDaqiService;


    /**
     * 通过id查询
     */
    @GetMapping("/get-by-id")
    public Result getById(String id) {
        MSamplingTaskDetection mSamplingTaskDetection = mSamplingTaskDetectionService.getByTaskId(id);
        if (ObjectUtil.isNull(mSamplingTaskDetection)) {
            return Result.successResult(null);
        }
        LambdaQueryWrapper<MSamplingTaskDetectionInfo> lambda = new QueryWrapper<MSamplingTaskDetectionInfo>().lambda();
        lambda.eq(MSamplingTaskDetectionInfo::getDelFlag, 0).eq(MSamplingTaskDetectionInfo::getSamplingTaskDetectionId, mSamplingTaskDetection.getId());
        List<MSamplingTaskDetectionInfo> list = mSamplingTaskDetectionInfoService.list(lambda);
        list.forEach(e -> {
            LambdaQueryWrapper<MSamplingTaskDetectionItem> lambdaItem = new QueryWrapper<MSamplingTaskDetectionItem>().lambda();
            lambdaItem.eq(MSamplingTaskDetectionItem::getDelFlag, 0).eq(MSamplingTaskDetectionItem::getSamplingTaskDetectionInfoId, e.getId());
            e.setItemList(mSamplingTaskDetectionItemService.list(lambdaItem));
        });
        mSamplingTaskDetection.setInfoList(list);
        return Result.successResult(mSamplingTaskDetection);
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    public Result save(@RequestBody MSamplingTaskDetection mSamplingTaskDetection) {
        if (StringUtil.isEmpty(mSamplingTaskDetection.getId())) {
            mSamplingTaskDetection.setStatus(1);
            mSamplingTaskDetection.setDelFlag(0);
            mSamplingTaskDetection.setGmtCreate(new Date());
            MSamplingTask mSamplingTask = mSamplingTaskService.getById(mSamplingTaskDetection.getSamplingTaskId());
            if (!StringUtil.isEmpty(mSamplingTaskDetection.getInspectReport())) {
                mSamplingTask.setStatus(4);
            } else {
                mSamplingTask.setStatus(3);
            }
            mSamplingTask.setGmtModified(new Date());
            mSamplingTaskService.updateById(mSamplingTask);
            mSamplingTaskDetectionService.save(mSamplingTaskDetection);
            if (!CollectionUtils.isEmpty(mSamplingTaskDetection.getInfoList())) {
                mSamplingTaskDetection.getInfoList().forEach(e -> {
                    e.setId(null);
                    e.setDelFlag(0);
                    e.setGmtCreate(new Date());
                    e.setSamplingTaskDetectionId(mSamplingTaskDetection.getId());
                    mSamplingTaskDetectionInfoService.save(e);
                    AtomicInteger count = new AtomicInteger();
                    if (!CollectionUtils.isEmpty(e.getItemList())) {
                        e.getItemList().forEach(k -> {
                            k.setId(null);
                            k.setDelFlag(0);
                            k.setGmtCreate(new Date());
                            k.setSamplingTaskDetectionInfoId(e.getId());
                            if (mSamplingTask.getType() == 2) {
                                JcyzSdShui jcyzSdShui = jcyzSdShuiService.getById(k.getYzId());
                                String query = "";
                                Integer type = 1;
                                switch (e.getCategory()) {
                                    case 1:
                                        query = jcyzSdShui.getYiQuery();
                                        type = jcyzSdShui.getYiQueryType();
                                        break;
                                    case 2:
                                        query = jcyzSdShui.getErQuery();
                                        type = jcyzSdShui.getErQueryType();
                                        break;
                                    case 3:
                                        query = jcyzSdShui.getSanQuery();
                                        type = jcyzSdShui.getSanQueryType();
                                        break;
                                    case 4:
                                        query = jcyzSdShui.getSiQuery();
                                        type = jcyzSdShui.getSiQueryType();
                                        break;
                                    case 5:
                                        query = jcyzSdShui.getWuQuery();
                                        type = jcyzSdShui.getWuQueryType();
                                        break;
                                    default:
                                        break;
                                }
                                if (ObjectUtil.isNotNull(jcyzSdShui) && ObjectUtil.isNotNull(type) && type == 2 && !StringUtil.isEmpty(query)) {
                                    Map<String, Object> env = new HashMap<String, Object>();
                                    env.put("'X'", k.getValue());
                                    if ((boolean) AviatorEvaluator.execute(query, env)) {
                                        k.setIsQualified(1);
                                    } else {
                                        k.setIsQualified(0);
                                        count.getAndIncrement();
                                    }
                                }
                            } else if (mSamplingTask.getType() == 1) {
                                JcyzSdTr jcyzSdTr = jcyzSdTrService.getById(k.getYzId());
                                Double value = null;
                                if (e.getTrType() == 1) {
                                    if (e.getCategory() == 1) {
                                        value = Double.parseDouble(jcyzSdTr.getYlydsxz());
                                    } else if (e.getCategory() == 2) {
                                        value = Double.parseDouble(jcyzSdTr.getElydsxz());
                                    }
                                } else if (e.getTrType() == 2) {
                                    if (e.getCategory() == 1) {
                                        value = Double.parseDouble(jcyzSdTr.getYlydgzz());
                                    } else if (e.getCategory() == 2) {
                                        value = Double.parseDouble(jcyzSdTr.getElydgzz());
                                    }
                                }
                                if (ObjectUtil.isNotNull(value)) {
                                    if (k.getValue().compareTo(value) > 0) {
                                        k.setIsQualified(1);
                                    } else {
                                        k.setIsQualified(0);
                                        count.getAndIncrement();
                                    }
                                }
                            } else if (mSamplingTask.getType() == 3) {
                                JcyzSdDaqi jcyzSdDaqi = jcyzSdDaqiService.getById(k.getYzId());
                                if (ObjectUtil.isNotNull(jcyzSdDaqi) && ObjectUtil.isNotNull(jcyzSdDaqi.getValue())) {
                                    if (k.getValue().compareTo(jcyzSdDaqi.getValue()) < 0) {
                                        k.setIsQualified(1);
                                    } else {
                                        k.setIsQualified(0);
                                        count.getAndIncrement();
                                    }
                                }
                            }
                            mSamplingTaskDetectionItemService.save(k);
                        });
                    }
                    e.setValue((e.getItemList().size() - count.doubleValue()) / e.getItemList().size());
                    mSamplingTaskDetectionInfoService.updateById(e);
                });
            }
        } else {
            return updateById(mSamplingTaskDetection);
        }
        return Result.successResult(null);
    }

    /**
     * 通过id删除
     */
    @GetMapping("/delete-by-id/{id}")
    public Result delete(@PathVariable(value = "id") String id) {

        mSamplingTaskDetectionItemService.removeByDetectionId(id);
        mSamplingTaskDetectionInfoService.removeByDetectionId(id);
        MSamplingTaskDetection mSamplingTaskDetection = mSamplingTaskDetectionService.getById(id);
        mSamplingTaskDetection.setDelFlag(1);
        mSamplingTaskDetection.setGmtModified(new Date());
        mSamplingTaskDetectionService.updateById(mSamplingTaskDetection);
        return Result.successResult(null);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public Result updateById(@RequestBody MSamplingTaskDetection mSamplingTaskDetection) {
        mSamplingTaskDetectionService.updateById(mSamplingTaskDetection);
        MSamplingTask mSamplingTask = mSamplingTaskService.getById(mSamplingTaskDetection.getSamplingTaskId());
        if (!StringUtil.isEmpty(mSamplingTaskDetection.getInspectReport())) {
            mSamplingTask.setStatus(4);
        } else {
            mSamplingTask.setStatus(3);
        }
        mSamplingTask.setGmtModified(new Date());
        mSamplingTaskService.updateById(mSamplingTask);
        mSamplingTaskDetectionItemService.removeByDetectionId(mSamplingTaskDetection.getId());
        mSamplingTaskDetectionInfoService.removeByDetectionId(mSamplingTaskDetection.getId());
        if (!CollectionUtils.isEmpty(mSamplingTaskDetection.getInfoList())) {
            mSamplingTaskDetection.getInfoList().forEach(e -> {
                e.setId(null);
                e.setDelFlag(0);
                e.setGmtCreate(new Date());
                e.setSamplingTaskDetectionId(mSamplingTaskDetection.getId());
                mSamplingTaskDetectionInfoService.save(e);
                AtomicInteger count = new AtomicInteger();
                if (!CollectionUtils.isEmpty(e.getItemList())) {
                    e.getItemList().forEach(k -> {
                        k.setId(null);
                        k.setDelFlag(0);
                        k.setGmtCreate(new Date());
                        k.setSamplingTaskDetectionInfoId(e.getId());
                        if (mSamplingTask.getType() == 2) {
                            JcyzSdShui jcyzSdShui = jcyzSdShuiService.getById(k.getYzId());
                            String query = "";
                            Integer type = 1;
                            switch (e.getCategory()) {
                                case 1:
                                    query = jcyzSdShui.getYiQuery();
                                    type = jcyzSdShui.getYiQueryType();
                                    break;
                                case 2:
                                    query = jcyzSdShui.getErQuery();
                                    type = jcyzSdShui.getErQueryType();
                                    break;
                                case 3:
                                    query = jcyzSdShui.getSanQuery();
                                    type = jcyzSdShui.getSanQueryType();
                                    break;
                                case 4:
                                    query = jcyzSdShui.getSiQuery();
                                    type = jcyzSdShui.getSiQueryType();
                                    break;
                                case 5:
                                    query = jcyzSdShui.getWuQuery();
                                    type = jcyzSdShui.getWuQueryType();
                                    break;
                                default:
                                    break;
                            }
                            if (ObjectUtil.isNotNull(jcyzSdShui) && ObjectUtil.isNotNull(type) && type == 2 && !StringUtil.isEmpty(query)) {
                                Map<String, Object> env = new HashMap<String, Object>();
                                env.put("'X'", k.getValue());
                                if ((boolean) AviatorEvaluator.execute(query, env)) {
                                    k.setIsQualified(1);
                                } else {
                                    k.setIsQualified(0);
                                    count.getAndIncrement();
                                }
                            }
                        } else if (mSamplingTask.getType() == 1) {
                            JcyzSdTr jcyzSdTr = jcyzSdTrService.getById(k.getYzId());
                            Double value = null;
                            if (e.getTrType() == 1) {
                                if (e.getCategory() == 1) {
                                    value = Double.parseDouble(jcyzSdTr.getYlydsxz());
                                } else if (e.getCategory() == 2) {
                                    value = Double.parseDouble(jcyzSdTr.getElydsxz());
                                }
                            } else if (e.getTrType() == 2) {
                                if (e.getCategory() == 1) {
                                    value = Double.parseDouble(jcyzSdTr.getYlydgzz());
                                } else if (e.getCategory() == 2) {
                                    value = Double.parseDouble(jcyzSdTr.getElydgzz());
                                }
                            }
                            if (ObjectUtil.isNotNull(value)) {
                                if (k.getValue().compareTo(value) > 0) {
                                    k.setIsQualified(1);
                                } else {
                                    k.setIsQualified(0);
                                    count.getAndIncrement();
                                }
                            }
                        } else if (mSamplingTask.getType() == 3) {
                            JcyzSdDaqi jcyzSdDaqi = jcyzSdDaqiService.getById(k.getYzId());
                            if (ObjectUtil.isNotNull(jcyzSdDaqi) && ObjectUtil.isNotNull(jcyzSdDaqi.getValue())) {
                                if (k.getValue().compareTo(jcyzSdDaqi.getValue()) > 0) {
                                    k.setIsQualified(1);
                                } else {
                                    k.setIsQualified(0);
                                    count.getAndIncrement();
                                }
                            }
                        }
                        mSamplingTaskDetectionItemService.save(k);
                    });
                }
                e.setValue((e.getItemList().size() - count.doubleValue()) / e.getItemList().size());
                mSamplingTaskDetectionInfoService.updateById(e);
            });
        }
        return Result.successResult(null);
    }


}
